<template>
  <div class="index">
    <div v-if="showForm" class="banner-box">
      <img class="banner" src="../../assets/image/banner/authBanner.png">
    </div>

    <div v-if="showForm" class="card-wrap">
      <div class="card">
        <div class="input-wrap">
          <div class="input-title">手机号码</div>
          <input
            v-model="form.phone"
            class="input-content"
            data-name="phone"
            placeholder="请输入手机号码"
            maxlength="11"
            pattern="[0-9]*"
            type="tel"
            @input="userInput"
          >
        </div>
        <SjCode :can-get-code="canGetCode" :tel="form.phone" @codeInput="codeInput"></SjCode>
        <SjButton
          :name-str="'登录'"
          :tip-str="'请输入完整信息'"
          :can-submit="canSubmit"
          style="margin-top:41px"
          @click="phoneLogin"
        >
        </SjButton>
      </div>

    </div>
  </div>
</template>

<script>
import SjButton from '@/components/SjButton/index.vue'
import SjCode from '@/components/SjCode/index.vue'
import commonUtils from '@/utils/common.js'
import { weChatFirstVisitAPI, userLoginAPI, testAPI } from '@/axios/api/auth'

export default {
  components: {
    SjCode,
    SjButton
  },
  data() {
    return {
      showForm: false, // 手机号登陆
      code: '', // 公众号授权 code

      form: {
        unitId: '', // 单位id
        phone: '', // 手机号
        code: '' // 验证码
      },

      auditId: '',
      invitePhone: ''
    }
  },
  computed: {
    canGetCode() {
      if ((/^1[3456789]\d{9}$/.test(this.form.phone))) {
        return true
      } else {
        return false
      }
    },
    canSubmit() {
      if (this.form.phone && this.form.code) {
        return true
      } else {
        return false
      }
    }
  },
  created() {
    /**
     * code ：有（公众号） 、无（手机号)
     * unitId: 单位ID
     * auditId：审核ID
     * invitePhone：邀请手机号
     */

    // local存储单位id
    const { unitId, auditId, invitePhone } = this.getIds()
    this.form.unitId = unitId
    this.unitId = unitId
    if (auditId > 0) {
      this.auditId = auditId
    }
    if (invitePhone > 0) {
      this.invitePhone = invitePhone
    }
     // 获取单位信息
    document.title = this.getUnitInfo().name

    this.code = commonUtils.getQueryStringByName('code')
    this.$store.commit('setPublic', !!this.code)
    if (this.code) {
      this.publicLogin(this.code, unitId) // 公众号登录
    } else {
      if (localStorage.getItem('visitorH5_token')) {
        this.checkLogin()
      } else {
        this.showForm = true
      }
    }
  },
  methods: {
    getIds() {
      localStorage.removeItem('visitorH5_unitId')
      const state = commonUtils.getQueryStringByName('state')
      console.log('state=' + state)
      if (state && state.split('a').length === 3) {
        const arr = state.split('a')
        localStorage.setItem('visitorH5_unitId', arr[0])
        return {
          unitId: arr[0],
          auditId: Number(arr[1]),
          invitePhone: Number(arr[2])
        }
      } else {
        console.log('链接参数为空')
        return false
      }
    },
    publicLogin(code, unitId) {
      weChatFirstVisitAPI({ code, unitId }).then(res => {
        // 3、信息认证
        if (res.bonded) {
          // 已认证 => 直接判断身份
          localStorage.setItem('visitorH5_token', res.token)
          localStorage.setItem('visitorH5_userInfo', JSON.stringify(res))
          this.checkIdentity(res)
        } else {
          // 未认证 => 去认证 => 判断身份
          this.$router.replace({ path: '/publicAuth', query: { unitId: this.unitId, auditId: this.auditId, invitePhone: this.invitePhone, openId: res.openId, headPicUrl: res.headPicUrl }})
        }
      }).catch(() => {
        console.log('公众号登录 catch')
      })
    },
    // 检查登录态
    checkLogin() {
      testAPI({ unitId: this.form.unitId }).then(res => { // 有token
        if (res.idCardNumber) {
          localStorage.setItem('visitorH5_userInfo', JSON.stringify(res))
          this.checkIdentity(res) // 已认证 => 直接判断身份
        } else {
          // 未认证 => 去认证 => 判断身份
          this.$router.replace({ path: '/phoneAuth', query: { unitId: this.unitId, auditId: this.auditId, phone: res.phone, invitePhone: this.invitePhone }})
        }
      }).catch(res => { // token过期
        this.showForm = true
      })
    },
    // 手机号登录
    phoneLogin() {
      userLoginAPI(this.form).then(res => {
        localStorage.setItem('visitorH5_token', res.token)
        // 3、信息认证
        if (res.idCardNumber) {
          localStorage.setItem('visitorH5_userInfo', JSON.stringify(res))
          this.checkIdentity(res)
        } else {
          // 未认证 => 去认证 => 判断身份
          this.$router.replace({ path: '/phoneAuth', query: { unitId: this.unitId, auditId: this.auditId, phone: res.phone, invitePhone: this.invitePhone }})
        }
      }).catch(() => {
        console.log('手机号登录 catch')
      })
    },
    // 检查身份, 访客 or 员工
    checkIdentity(res) {
      if (res.isStaff) { // 员工
        if (this.auditId) {
          this.$router.replace({ path: '/adminOrderDetail', query: { unitId: this.unitId, auditId: this.auditId }})
        } else {
          this.$router.replace({ path: '/adminOrderList' })
        }
      } else {
        this.$router.replace({ path: '/visitor', query: { invitePhone: this.invitePhone }}) // 访客
      }
    },
    userInput(e) {
      this.form[e.target.dataset.name] = e.target.value.replace(/\s*/g, '')
    },
    codeInput(e) {
      this.form.code = e.value
    }
  }
}
</script>

<style lang="scss" scoped>
.index {
  .banner-box {
    position: relative;
    width: 100vw;
    height: 50.13vw;
    .banner {
      width: 100%;
      display: block;
    }
  }
}
.card-wrap {
  position: relative;
  z-index: 1;
  padding: 0 15px;
  .card {
    padding: 7px 16px 24px;
    border-radius: 12px;
    box-shadow: 0px 3px 6px rgba(38, 126, 255, 0.2);
    background: #ffffff;

    .input-wrap {
      height: 70px;
      padding: 16px 0 8px;
      border-bottom: 1px solid #f1f2f3;

      .input-title {
        height: 16px;
        line-height: 16px;
        font-size: 11px;
        color: #707070;
      }
      .input-content {
        width: 100%;
        margin-top: 8px;
        height: 21px;
        line-height: 21px;
        font-size: 15px;
        color: black;
      }
    }
  }
}
</style>
